package com.jinyijia.admin.interfaces;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jinyijia.admin.config.Constant;
import com.jinyijia.admin.interfaces.dto.CategoryAddDTO;
import com.jinyijia.admin.interfaces.utils.HttpHeadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestOperations;

import java.util.Objects;

/**
 * Created by yangrd on 2018/3/11
 * 类目接口
 **/
@RestController
@RequestMapping(Constant.Path.CATEGORIES)
public class CategoryController {

    @Autowired
    private RestOperations restOperations;

    @Value("${jinYiJia.api.categories}")
    private String apiPath;

    /**
     * 获取类目树
     */
    @GetMapping
    public ResponseEntity getTree() {
        return restOperations.getForEntity(apiPath, JSONArray.class);
    }

    /**
     * 父节点获取子类目
     */
    @GetMapping("/{pid}")
    public ResponseEntity getChildren(@PathVariable Integer pid){
        String url = apiPath + "/" + pid + "/children";
        JSONArray array = restOperations.getForEntity(url, JSONArray.class).getBody();
        return ResponseEntity.ok(array);
    }

    /**
     * 添加类目
     */
    @PostMapping
    public ResponseEntity addCategory(@RequestBody CategoryAddDTO dto){
        StringBuilder url = new StringBuilder(apiPath).append("?name=").append(dto.getName());
        if (Objects.nonNull(dto.getSort())) {
            url.append("&sort=").append(dto.getSort());
        }
        if (Objects.nonNull(dto.getParentId())) {
            url.append("&parentId=").append(dto.getParentId());
        }
        return ResponseEntity.ok(restOperations.postForEntity(url.toString(), null, Object.class).getBody());
    }

    /**
     * 删除类目
     * @param id
     * @return
     */
    @DeleteMapping(value = "/{id}")
    public ResponseEntity deleteCategory(@PathVariable Integer id) {
        String url = apiPath + "/" + id;
        HttpEntity<String> httpEntity = HttpHeadUtil.addHeader();
        String response = restOperations.exchange(url.toString(), HttpMethod.DELETE, httpEntity, String.class).getBody();
        return ResponseEntity.ok(response);
    }

    /**
     * 编辑类目
     * @param dto
     * @return
     */
    @PutMapping
    public ResponseEntity editCategory(@RequestBody CategoryAddDTO dto) {
        StringBuilder url = new StringBuilder(apiPath).append("/").append(dto.getId());
        if (Objects.nonNull(dto.getName())) {
            url.append("?name=").append(dto.getName());
        }
        if (Objects.nonNull(dto.getSort())) {
            url.append("&sort=").append(dto.getSort());
        }
        restOperations.put(url.toString(), null);
        return ResponseEntity.ok("ok");
    }
}
